# Copyright 2025 Stanford University, NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License
# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing permissions and limitations under
# the License.

set(REALM_VERSION @Realm_VERSION@)

@PACKAGE_INIT@

# Allow the application developer to choose between static and shared libraries
# if available by specifying 'static' or 'shared' component in find_package

set(realm_known_comps static shared)
set(realm_static_comp NO)
set(realm_shared_comp NO)
for(_comp IN LISTS ${CMAKE_FIND_PACKAGE_NAME}_COMPONENTS)
if(_comp IN_LIST realm_known_comps)
  set(realm_${_comp}_comp YES)
else()
  set(${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE
      "${CMAKE_FIND_PACKAGE_NAME} does not recognize ${_comp}"
  )
  set(${CMAKE_FIND_PACKAGE_NAME}_FOUND FALSE)
  return()
endif()
endfor()

if(realm_static_comp AND realm_shared_comp)
  set(${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE
      "${CMAKE_FIND_PACKAGE_NAME} cannot request static and shared simultaneously"
  )
  set(${CMAKE_FIND_PACKAGE_NAME}_FOUND FALSE)
  return()
endif()

macro(realm_load_targets type)
  if(NOT EXISTS "${CMAKE_CURRENT_LIST_DIR}/Realm-${type}-targets.cmake")
    set(${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE
        "${CMAKE_FIND_PACKAGE_NAME} '${type}' libraries requested, but not found"
    )
    set(${CMAKE_FIND_PACKAGE_NAME}_FOUND FALSE)
    return()
  endif()
  include("${CMAKE_CURRENT_LIST_DIR}/Realm-${type}-targets.cmake")
  set(${CMAKE_FIND_PACKAGE_NAME}_${type}_FOUND TRUE)
endmacro()

# If the user specified a static or shared, use that, otherwise guess with a reasonable default
if(realm_static_comp)
  realm_load_targets(static)
elseif(realm_shared_comp)
  realm_load_targets(shared)
elseif(BUILD_SHARED_LIBS)
  if(EXISTS "${CMAKE_CURRENT_LIST_DIR}/Realm-shared-targets.cmake")
    realm_load_targets(shared)
  else()
    realm_load_targets(static)
  endif()
else()
  if(EXISTS "${CMAKE_CURRENT_LIST_DIR}/Realm-static-targets.cmake")
    realm_load_targets(static)
  else()
    realm_load_targets(shared)
  endif()
endif()

include(CMakeFindDependencyMacro)
# Find all the static library dependencies needed
# TODO(cperry): need to enumerate all the dependencies linked in for the static build
if(${CMAKE_FIND_PACKAGE_NAME}_static_FOUND)
  foreach (_dep IN LISTS @REALM_STATIC_DEPENDS@)
   find_dependency(${_dep})
  endforeach()
endif()

check_required_components(realm)
